<?php

namespace App\Http\Controllers\Api;

use App\Exceptions\BusinessException;
use App\Models\VerifyModel;
use App\Utils\ResponseEnum;
use App\Utils\Sms\SmsInterface;
use App\Utils\Sms\UnKnownSms;
use App\Utils\Sms\ZhuTongSms;
use Carbon\Carbon;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Http\JsonResponse;

class VerifyController extends ApiController
{
    // 验证码有效间隔
    const VALID_INTERVAL = 5 * 60;

    /**
     * 获取验证码
     * @return JsonResponse
     * @throws BusinessException
     * @throws GuzzleException
     */
    public function getVerify(): JsonResponse
    {
       $mobile = $this->verifyString('mobile');
        $verifyCode = rand(1000, 9999);
        VerifyModel::create(['mobile' => $mobile, 'verify' => $verifyCode, 'app_name' => '绒博汇']);
        $Sms = new ZhuTongSms('绒博汇');
        if (!$Sms->send($mobile, $verifyCode))
            return $this->fail(ResponseEnum::HTTP_ERROR);
        return $this->success(['verify' => $verifyCode]);
    }

    /**
     * 校验验证码有效性
     * @param string $mobile
     * @param int $verify
     * @return bool
     */
    public static function checkVerifyValid(string $mobile, int $verify): bool
    {
        $row = VerifyModel::where('mobile', $mobile)->orderByDesc('id')->first();
        if ($row && $row->verify == $verify) {
            $timestamp = Carbon::parse($row->created_at)->getTimestamp();
            return !(time() - $timestamp > self::VALID_INTERVAL);
        } else
            return false;
    }
}
